/*
 * @Description: 单位-全宗-档案类型-层级 导航
 * @Author: Rfan
 * @Date: 2022-02-17 14:06:25
 * @LastEditTime: 2023-02-27 09:25:22
 */

import { memo, useEffect, useState } from 'react';
import { Select } from 'antd';
import classNames from 'classnames/bind';
import { observer } from 'mobx-react-lite';
import { appState } from '@/store/mobx';
import { fetchFondsListByUnitId } from '@/api/fonds';
import { selectItemByKey } from '@/utils/list';
import ATLevelNav from '../ATLevelNav';
import type { IFond } from '@/interfaces/fond';

import styles from './index.module.scss';

const cx = classNames.bind(styles);

const { Option } = Select;

export interface UFALNavProps {
  onChange: any;
  // 档案类型的类型
  type?: number;
  hideLowest?: boolean;
}

const UFALNav = (props: UFALNavProps) => {
  const { type = 1, hideLowest = true, onChange } = props;

  // 全宗列表
  const [fondsList, setFondsList] = useState([]);
  // 选中的全宗
  const [selectFondId, setSelectFondId] = useState(0);

  // 加载时获取全宗列表，获取成功后默认选中第一条并把第一条返回出去
  useEffect(() => {
    const { unitId } = appState;
    if (unitId) {
      fetchFondsListByUnitId(unitId).then((res) => {
        const _fondList: IFond[] = res.data;
        setFondsList(_fondList);
        setSelectFondId(_fondList[0].id);
      });
    }
  }, [appState.unitId]);

  /**
   * @description: 切换全宗
   * @param {number} val 选中的全宗
   */
  const handleFondChange = (val: number) => {
    setSelectFondId(val);
  };

  /**
   * @description: 档案类型，层级切换
   * @param {any} param1
   */
  const handleATChange = ({ _atId, atItem, _levelId, levelItem }: any) => {
    onChange({ fondItem: selectItemByKey(selectFondId, fondsList), atItem, levelItem });
  };

  return (
    <div className={cx('container')}>
      <Select value={selectFondId} style={{ width: '100%' }} onChange={handleFondChange}>
        {fondsList.map((fond) => (
          <Option key={fond.id} value={fond.id}>
            {fond.fondName}
          </Option>
        ))}
      </Select>
      <h6 className={cx('at-header')}>档案类型列表</h6>
      <div className={cx('at-list-wrap')}>
        <ATLevelNav
          activeFond={selectFondId}
          type={type}
          onChange={handleATChange}
          hideLowest={hideLowest}
        />
      </div>
    </div>
  );
};

export default memo(observer(UFALNav));
